import os
import shutil
import logging

#!/usr/bin/env python3

# 设置日志记录
log_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data_move.log')
# 使用 'w' 模式来覆盖旧的日志文件
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s - %(message)s',
                    handlers=[
                        logging.FileHandler(log_file, mode='w'),
                        logging.StreamHandler()
                    ])

# 设置源文件夹和目标文件夹路径
src_folder = "/root/data/Outdoor/OTS"  # 修改为图片所在的文件夹路径
dst_folder = "/root/data/Outdoor/hazy_smaller"  # 修改为移动目标文件夹路径

# 需要匹配的文件名前缀
prefixes = ['8365', '2891', '5778', '2557', '2890', '4782']
# 将前缀转换为元组以用于 startswith 方法
prefixes_tuple = tuple(prefixes)

# 确保目标文件夹存在
if not os.path.exists(dst_folder):
    os.makedirs(dst_folder)
    logging.info(f"Created destination folder: {dst_folder}")

# 获取文件名并排序
try:
    logging.info(f"Scanning and sorting source folder: {src_folder}")
    filenames = sorted(os.listdir(src_folder))
    logging.info(f"Found {len(filenames)} files.")
except FileNotFoundError:
    logging.error(f"Source folder not found: {src_folder}")
    exit()


# 遍历源文件夹中的文件
moved_count = 0
for filename in filenames:
    # 检查文件名是否以指定的前缀之一开头
    if filename.startswith(prefixes_tuple):
        src_path = os.path.join(src_folder, filename)
        dst_path = os.path.join(dst_folder, filename)

        # 检查是否为文件
        if os.path.isfile(src_path):
            try:
                shutil.move(src_path, dst_path)
                logging.info(f"Moved '{filename}' to {dst_folder}")
                moved_count += 1
            except Exception as e:
                logging.error(f"Failed to move '{filename}': {e}")

logging.info(f"Script finished. Moved {moved_count} files in total.")
